package com.my.vertx.tcp;

import io.netty.handler.logging.ByteBufFormat;
import io.vertx.core.Vertx;
import io.vertx.core.net.NetClient;
import io.vertx.core.net.NetClientOptions;
import io.vertx.core.net.NetSocket;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author: marshal
 * @date: 2023-08-04 2:17
 */
@Slf4j
public class VertxTcpClientReconnectTest {

    /**
     * 重连次数
     */
    private static final AtomicInteger RECONNECT_ATTEMPTS = new AtomicInteger(0);
    /**
     * 最大重连次数
     */
    private static final int MAX_RECONNECT_ATTEMPTS = 3;
    /**
     * 重连间隔
     */
    private static final Integer RECONNECT_INTERVAL_MS = 200;
    private static final String host = "127.0.0.1";
    private static final int port = 9800;
    private static final Vertx vertx = Vertx.vertx();

    public static void main(String[] args) {
        connect(host, port);
    }

    private static void connect(String host, int port) {
        if (RECONNECT_ATTEMPTS.get() >= MAX_RECONNECT_ATTEMPTS) {
            return;
        }
        NetClientOptions options = new NetClientOptions()
                .setLogActivity(true)
                .setActivityLogDataFormat(ByteBufFormat.SIMPLE)
                .setConnectTimeout(10000)
                .setReconnectAttempts(10)
                .setReconnectInterval(500);
        // 创建TCP Client 对象
        NetClient client = vertx.createNetClient(options);
        // 创建连接
        client.connect(port, host, handler -> {
            // 连接成功
            if (handler.succeeded()) {
                NetSocket socket = handler.result();
                // socket 成功建立连接后的处理
                socket.handler(bufferHandler -> {

                });
                // socket 异常处理
                socket.exceptionHandler(throwableHandler -> {

                });
                // socket 关闭处理
                socket.closeHandler(closeHandler -> {

                });
            } else {
                // 重连
                int i = RECONNECT_ATTEMPTS.incrementAndGet();
                vertx.setTimer(RECONNECT_INTERVAL_MS, timerId -> connect(host, port));
                log.debug("第 {} 次重连", i);
                if (i >= MAX_RECONNECT_ATTEMPTS) {
                    log.debug("连接失败");
                    System.exit(1);
                }
            }
        });
    }
}
